const port = 9501;
const Koa = require('koa2')
// 路由
const route = require('koa-route')
// koa封装的websocket这是官网（很简单有时间去看一下https://www.npmjs.com/package/koa-websocket）
const websockify = require('koa-websocket')
const superagent = require('superagent')

const bilibili = require('./danmu/bilibili')
const douyu = require('./danmu/douyu')
const huya = require('./danmu/huya')

const app = websockify(new Koa());


app.ws.use(function (ctx, next) {
    ctx.websocket.send(JSON.stringify({content:'连接成功'}));
    return next(ctx)
})
app.ws.use(route.all('/douyu', (ctx) => {
    /**接收消息*/
    const roomId = ctx.query.roomId

    let client = new douyu(roomId)
    client.on('message', res => {
        // console.log(res)
        ctx.websocket.send(JSON.stringify(res))
    })
    client.start()
    ctx.websocket.on('message', function (message) {
        console.log(message);
        // 返回给前端的数据
        let data = JSON.stringify({
            id: Math.ceil(Math.random() * 1000),
            time: parseInt(new Date() / 1000)
        })
        ctx.websocket.send(data);
    })
}));

app.ws.use(route.all('/bilibili', (ctx) => {
    /**接收消息*/
    const roomId = ctx.query.roomId
    // console.log(roomId)

    let client = new bilibili(roomId)
    client.on('message', res => {
        console.log(res)
        ctx.websocket.send(JSON.stringify(res))
    })
    client.start()


    ctx.websocket.on('message', function (message) {
        // console.log(message);
        // 返回给前端的数据
        let data = JSON.stringify({
            id: Math.ceil(Math.random() * 1000),
            time: parseInt(new Date() / 1000)
        })
        ctx.websocket.send(data);
    })
    ctx.websocket.on('close', res => {
        console.log('断开连接')
        client.stop()
        client = null
    })
}));

app.ws.use(route.all('/huya', (ctx) => {
    /**接收消息*/
    const roomId = ctx.query.roomId


    let client = new huya(roomId)
    client.on('connect', () => {
        console.log(`已连接huya ${roomId}房间弹幕~`)
    })

    client.on('message', msg => {
        // console.log(msg)
        ctx.websocket.send(JSON.stringify(msg))
    })

    client.on('error', e => {
        console.log(e)
    })

    client.on('close', () => {
        console.log('close')
    })
    client.start()

    ctx.websocket.on('message', function (message) {
        console.log(message);
        // 返回给前端的数据
        let data = JSON.stringify({
            id: Math.ceil(Math.random() * 1000),
            time: parseInt(new Date() / 1000)
        })
        ctx.websocket.send(data);
    })
    ctx.websocket.on('close', res => {
        console.log('断开连接')
        client.stop()
        client = null
    })
}));

app.use(async (ctx) => {

    // console.log(ctx.url)
    const fileName = ctx.url.slice(ctx.url.lastIndexOf('/') + 1)
    let url = 'http://i1.hdslb.com/bfs/face/' + fileName
    // console.log(url)


    const img2Base64 = await new Promise(async function (resolve, reject) {
        await superagent.get(url).buffer(true).parse((res) => {
            let buffer = [];
            res.on('data', (chunk) => {
                // console.log(chunk)
                buffer.push(chunk);
            });
            res.on('end', () => {
                    const data = Buffer.concat(buffer);
                    // fs.writeFileSync('../../public/' + fileName, data)
                    // ctx.body = img2Base64;
                    ctx.body = data;
                    // process.stdout.write(data);
                    const base64Img = 'data:image/jpeg;base64,' + data.toString('base64');
                    resolve(base64Img)
                }
            );
        });
    })


});


app.listen(port, () => {
    console.log("localhost:" + port);
});
